package com.xy.novelmanagement.websocket;

import com.alibaba.fastjson.JSONObject;
import com.xy.novelmanagement.service.IBQGSpider;
import com.xy.utils.JsonValidatorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

@Slf4j
@Component
public class BQGSocket extends TextWebSocketHandler {
		@Autowired
		private ThreadPoolTaskScheduler threadPoolTaskScheduler;
		private ScheduledFuture<?> future;

		private static Map<String, WebSocketSession> userIdSessionMap = new ConcurrentHashMap();
		private static Map<WebSocketSession, String> sessionUserIdMap = new ConcurrentHashMap<>();

		private static IBQGSpider ibqgSpider;
		@Autowired
		public void setUserMapper(IBQGSpider ibqgSpider){
				BQGSocket.ibqgSpider = ibqgSpider;
		}

		/*
		 * url：/bqg
		 * */
		@Override
		protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
				String payload = message.getPayload();
				log.info("websocket请求参数payload:{}", payload);
				try {
						if (JsonValidatorUtil.getInstance().validate(payload)) {
								JSONObject jsonObject = JSONObject.parseObject(payload);
								String type = jsonObject.getString("type");
								String num = jsonObject.getString("num");
								String delivery = jsonObject.getString("delivery");
								
								//是否设置实时爬
								if ("true".equals(delivery)) {
										log.info("注册websocket连接");
										String userId = "BQG"+ UUID.randomUUID().toString();
										log.info("userId:{}注册session:{}", userId, session.getId());
										userIdSessionMap.put(userId, session);
										sessionUserIdMap.put(session, userId);
										log.info("service="+ibqgSpider);
										ibqgSpider.spiderNovel(type,num,userId);
								}else {
										log.info("注册websocket连接");
										String userId = "BQG_ASYN";
										log.info("userId:{}注册session:{}", userId, session.getId());
										userIdSessionMap.put(userId, session);
										sessionUserIdMap.put(session, userId);
								}
						} else {
								if (payload.equals("status")) {
										session.sendMessage(new TextMessage("连接成功！"));
								} else {
										session.sendMessage(new TextMessage(payload + " 不是JSON格式！"));
								}
						}
				} catch (IOException e) {
						log.error("笔趣阁websocket发生了错误：{}", e.getMessage(), e);
						session.sendMessage(new TextMessage(e.getMessage()));
				}
		}

		//定时任务获取session
		public static Map<String, WebSocketSession> getUserIdSessionMap() {
				return userIdSessionMap;
		}

		@Override
		public void afterConnectionEstablished(WebSocketSession session) throws Exception {
				super.afterConnectionEstablished(session);
		}

		@Override
		public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {

				//连接关闭后移除
				/*String userId = sessionUserIdMap.get(session);
				userIdSessionMap.remove(userId);
				log.info("websocket session:{}关闭原因:{}",session,status);*/
		}
}
